package com.moive.news.tqnewsapplication.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.Adapter.BaseListAdapter;
import com.moive.news.tqnewsapplication.base.BaseFragment;
import com.moive.news.tqnewsapplication.entity.NewsInfo;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.ui.activity.NewsDteilsAcitivity;
import com.moive.news.tqnewsapplication.ui.activity.QiushiDetilsActivity;
import com.moive.news.tqnewsapplication.utils.DateUtil;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/1/8.
 */

public class QiuShiFragment extends BaseFragment implements SecondXListView.IXListViewListener {
    @BindView(R.id.pub_all_listview)
    SecondXListView pubAllListview;
    @BindView(R.id.pub_all_myText)
    TextView pubAllMyText;
    Unbinder unbinder;
    private List<NewsInfo.RowsBean> list = new ArrayList<>();
    private Gson gson = new Gson();
    private int page = 1;
    private boolean isfresh = true;
    private QiushiAdpater adapter;
    private static final String TAG = "XiaodaoFragment";
    private View NewsListView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        NewsListView = inflater.inflate(R.layout.layout_recyclerview, container, false);
        unbinder = ButterKnife.bind(this, NewsListView);
        LogUtil.i("lidaming","onCreateView");
        return NewsListView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtil.i("lidaming","onViewCreated");
        init();
    }
    private void init() {
        adapter = new QiushiAdpater(getActivity());
        pubAllListview.setAdapter(adapter);
        pubAllListview.setXListViewListener(this);
        pubAllListview.setPullLoadEnable(true);
        getdata();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.i("lidaming","onDestroyView");
        unbinder.unbind();
    }

    public void getdata() {
        OkHttpUtils.get()
                .addParams("token", PreferenceUtil.getString("token",""))
                .url(BaseApi.NEWS_TYPE_ITEM)
                .addParams("page", page + "")
                .addParams("rows", "10")
                .addParams("category", "糗事")
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.i(TAG, "error=" + e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, "response=" + response.toString());
                try {
                    JSONObject j = new JSONObject(response);
                    JSONArray j2 = j.getJSONArray("rows");
                    if (j2 != null || j2.length() != 0) {
                        for (int i = 0; i < j2.length(); i++) {
                            JSONObject j3 = (JSONObject) j2.opt(i);
                            NewsInfo.RowsBean bean = gson.fromJson(j3 + "", NewsInfo.RowsBean.class);
                            list.add(bean);
                        }
                        if (list != null & list.size() > 0) {

                            adapter.addItems(list);
                        }
                    } else {
                        ToastUtils.ShortToast("没有更多数据了！");
                    }
                    pubAllListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(list.get(position-1));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden){
            LogUtil.i("lidaming","onHiddenChanged");
            JCVideoPlayer.releaseAllVideos();
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        isfresh = true;
        list.clear();
        getdata();
        adapter.notifyDataSetChanged();
        stopOnLoad();
    }

    private void stopOnLoad() {
        pubAllListview.stopRefresh();
        pubAllListview.stopLoadMore();
        pubAllListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                isfresh = false;
                getdata();
                adapter.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }

    public class QiushiAdpater extends BaseListAdapter<NewsInfo.RowsBean> {
        public static final int TYPE_1 = 0;
        public static final int TYPE_2 = 1;
        public static final int TYPE_3 = 2;
        private Context context;
        public QiushiAdpater(Context context) {
            this.context = context;
        }
        @Override
        protected View getItemView(int position, View convertView, ViewGroup parent, List<NewsInfo.RowsBean> item) {
            ViewHolder01 viewHolder01 = null;
            ViewHolder02 viewHolder02 = null;
            ViewHolder03 viewHolder03 = null;
            int type = getItemViewType(position);
            if (convertView == null) {
                switch (type) {
                    case TYPE_1:
                        viewHolder01 = new ViewHolder01();
                        convertView = LayoutInflater.from(context).inflate(R.layout.qiushi_item_01, null);
                        viewHolder01.qiushi_item01_img = convertView.findViewById(R.id.qiushi_item01_img);
                        viewHolder01.ad_mypro_nine = convertView.findViewById(R.id.ad_mypro_nine);
                        viewHolder01.qiushi_item01_nichen = convertView.findViewById(R.id.qiushi_item01_nichen);
                        viewHolder01.qiushi_item01_time = convertView.findViewById(R.id.qiushi_item01_time);
                        viewHolder01.qiushi_item01_desrc = convertView.findViewById(R.id.qiushi_item01_desrc);
                        viewHolder01.qiushi_item01_fenxiang_ll = convertView.findViewById(R.id.qiushi_item01_fenxiang_ll);
                        viewHolder01.qiushi_item01_pinglun_ll = convertView.findViewById(R.id.qiushi_item01_pinglun_ll);
                        viewHolder01.qiushi_item01_pinglun_text = convertView.findViewById(R.id.qiushi_item01_pinglun_text);
                        viewHolder01.qiushi_item01_dianzan_ll = convertView.findViewById(R.id.qiushi_item01_dianzan_ll);
                        viewHolder01.qiushi_item01_dianzan_text = convertView.findViewById(R.id.qiushi_item01_dianzan_text);
                        viewHolder01.mypro_dianzan_img = convertView.findViewById(R.id.mypro_dianzan_img);
                        convertView.setTag(viewHolder01);
                        break;
                    case TYPE_2:
                        viewHolder02 = new ViewHolder02();
                        convertView = LayoutInflater.from(context).inflate(R.layout.qiushi_item_02, null);
                        viewHolder02.qiushi_item02_img = convertView.findViewById(R.id.qiushi_item02_img);
                        viewHolder02.qiushi_item02_nichen = convertView.findViewById(R.id.qiushi_item02_nichen);
                        viewHolder02.qiushi_item02_time = convertView.findViewById(R.id.qiushi_item02_time);
                        viewHolder02.qiushi_item02_pinglun_ll = convertView.findViewById(R.id.qiushi_item02_pinglun_ll);
                        viewHolder02.qiushi_item02_pinglun_text = convertView.findViewById(R.id.qiushi_item02_pinglun_text);
                        viewHolder02.qiushi_item02_desrc = convertView.findViewById(R.id.qiushi_item02_desrc);
                        viewHolder02.qiushi_item02_dianzan_img = convertView.findViewById(R.id.qiushi_item02_dianzan_img);
                        viewHolder02.qiushi_item02_dianzan_text = convertView.findViewById(R.id.qiushi_item02_dianzan_text);
                        viewHolder02.qiushi_item02_fenxiang_ll = convertView.findViewById(R.id.qiushi_item02_fenxiang_ll);
                        viewHolder02.qiushi_item02_dianzan_ll = convertView.findViewById(R.id.qiushi_item02_dianzan_ll);
                        convertView.setTag(viewHolder02);
                        break;
                    case TYPE_3:
                        viewHolder03 = new ViewHolder03();
                        convertView = LayoutInflater.from(context).inflate(R.layout.qiushi_item_03, null);
                        viewHolder03.qiushi_item03_img = convertView.findViewById(R.id.qiushi_item03_img);
                        viewHolder03.qiushi_item03_nichen = convertView.findViewById(R.id.qiushi_item03_nichen);
                        viewHolder03.qiushi_item03_time = convertView.findViewById(R.id.qiushi_item03_time);
                        viewHolder03.qiushi_item03_desrc = convertView.findViewById(R.id.qiushi_item03_desrc);
                        viewHolder03.videoplayer = convertView.findViewById(R.id.videoplayer);
                        viewHolder03.qiushi_item03_fenxiang_ll = convertView.findViewById(R.id.qiushi_item03_fenxiang_ll);
                        viewHolder03.qiushi_item03_pinglun_ll = convertView.findViewById(R.id.qiushi_item03_pinglun_ll);
                        viewHolder03.qiushi_item03_pinglun_text = convertView.findViewById(R.id.qiushi_item03_pinglun_text);
                        viewHolder03.qiushi_item03_dianzan_ll = convertView.findViewById(R.id.qiushi_item03_dianzan_ll);
                        viewHolder03.qiushi_item03_dianzan_text = convertView.findViewById(R.id.qiushi_item03_dianzan_text);
                        viewHolder03.qiushi_item03_dianzan_img = convertView.findViewById(R.id.qiushi_item03_dianzan_img);
                        convertView.setTag(viewHolder03);
                        break;
                }
            } else {
                switch (type) {
                    case TYPE_1:
                        viewHolder01 = (ViewHolder01) convertView.getTag();
                        break;
                    case TYPE_2:
                        viewHolder02 = (ViewHolder02) convertView.getTag();
                        break;
                    case TYPE_3:
                        viewHolder03 = (ViewHolder03) convertView.getTag();
                        break;
                }
            }
            switch (type) {
                case TYPE_1:
                    Glide.with(context)
                            .load(item.get(position).getUserHeadImg())
                            .centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.icon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(viewHolder01.qiushi_item01_img);
                    viewHolder01.qiushi_item01_nichen.setText(item.get(position).getUserNickName());
                    String newtime = DateUtil.getDescriptionTimeFromTimestamp(item.get(position).getTime());
                    viewHolder01.qiushi_item01_time.setText(newtime);
                    try {
                        String comment = URLDecoder.decode(item.get(position).getContent(), "UTF-8");
                        viewHolder01.qiushi_item01_desrc.setText(comment);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    viewHolder01.qiushi_item01_fenxiang_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                    viewHolder01.qiushi_item01_pinglun_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(list.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    if (item.get(position).getIsCurrentUserLike()==0){
                        viewHolder01.mypro_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan01);
                    }else {
                        viewHolder01.mypro_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan02);
                    }
                    viewHolder01.qiushi_item01_pinglun_text.setText(item.get(position).getCommentCount()+"");
                    viewHolder01.qiushi_item01_dianzan_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    viewHolder01.qiushi_item01_dianzan_text.setText(item.get(position).getLikeCount()+"");
                    ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                    List<NewsInfo.RowsBean.ImageInfo> list = item.get(position).getImages();
                    for (NewsInfo.RowsBean.ImageInfo imagesBean : list) {
                        ImageInfo info = new ImageInfo();
                        info.setThumbnailUrl(imagesBean.getThumbUrl());
                        info.setBigImageUrl(imagesBean.getLargeUrl());
                        imageInfo.add(info);
                    }
                    viewHolder01.ad_mypro_nine.setAdapter(new NineGridViewClickAdapter(context, imageInfo));
                    break;
                case TYPE_2:
                    Glide.with(context)
                            .load(item.get(position).getUserHeadImg())
                            .centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.icon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(viewHolder02.qiushi_item02_img);

                    viewHolder02.qiushi_item02_nichen.setText(item.get(position).getUserNickName());
                    String newtime1 = DateUtil.getDescriptionTimeFromTimestamp(item.get(position).getTime());
                    viewHolder02.qiushi_item02_time.setText(newtime1);
                    try {
                        if (!TextUtils.isEmpty(item.get(position).getContent())){
                            String comment = URLDecoder.decode(item.get(position).getContent(), "UTF-8");
                            viewHolder02.qiushi_item02_desrc.setText(comment);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    viewHolder02.qiushi_item02_fenxiang_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    viewHolder02.qiushi_item02_pinglun_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    if (item.get(position).getIsCurrentUserLike()==0){
                        viewHolder02.qiushi_item02_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan01);
                    }else {
                        viewHolder02.qiushi_item02_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan02);
                    }
                    viewHolder02.qiushi_item02_pinglun_text.setText(item.get(position).getCommentCount()+"");
                    viewHolder02.qiushi_item02_dianzan_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    viewHolder02.qiushi_item02_dianzan_text.setText(item.get(position).getLikeCount()+"");
                    break;
                case TYPE_3:
                    viewHolder03.qiushi_item03_nichen.setText(item.get(position).getUserNickName());
                    Glide.with(context)
                            .load(item.get(position).getUserHeadImg())
                            .centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.icon)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(viewHolder03.qiushi_item03_img);
                    String time = DateUtil.getDescriptionTimeFromTimestamp(item.get(position).getTime());
                    viewHolder03.qiushi_item03_time.setText(time);
                    try {
                        String comment = URLDecoder.decode(item.get(position).getContent(), "UTF-8");
                        viewHolder03.qiushi_item03_desrc.setText(comment);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    viewHolder03.qiushi_item03_fenxiang_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    viewHolder03.qiushi_item03_pinglun_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    if (item.get(position).getIsCurrentUserLike()==0){
                        viewHolder03.qiushi_item03_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan01);
                    }else {
                        viewHolder03.qiushi_item03_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan02);
                    }
                    viewHolder03.qiushi_item03_pinglun_text.setText(item.get(position).getCommentCount()+"");
                    viewHolder03.qiushi_item03_dianzan_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getActivity(), QiushiDetilsActivity.class);
                            Bundle b = new Bundle();
                            String s=gson.toJson(item.get(position));
                            b.putString("url", s);
                            LogUtil.i("lidaming", s);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    });
                    viewHolder03.qiushi_item03_dianzan_text.setText(item.get(position).getLikeCount()+"");
                    boolean setUp = viewHolder03.videoplayer.setUp(item.get(position).getMp4Url(),
                            JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                    if (setUp) {
                        Glide.with(context).load(item.get(position).getMediumCover()).into(viewHolder03.videoplayer.thumbImageView);
                    }
                    break;
            }
            return convertView;
        }
        @Override
        public int getItemViewType(int position) {
            if (list != null & list.size() > 0) {
                if (list.get(position).getMediaType() == 0) {
                    return TYPE_2;
                } else if (list.get(position).getMediaType() == 1 || list.get(position).getMediaType() == 2
                        || list.get(position).getMediaType() == 4) {
                    return TYPE_1;
                }
                {
                    return TYPE_3;
                }
            }
            return TYPE_1;
        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }
        class ViewHolder01 {
            private CircleImageView qiushi_item01_img;
            private TextView qiushi_item01_nichen;
            private TextView qiushi_item01_time;
            private TextView qiushi_item01_desrc;
            private NineGridView ad_mypro_nine;
            private LinearLayout qiushi_item01_fenxiang_ll;
            private LinearLayout qiushi_item01_pinglun_ll;
            private TextView qiushi_item01_pinglun_text;
            private LinearLayout qiushi_item01_dianzan_ll;
            private TextView qiushi_item01_dianzan_text;
            private ImageView mypro_dianzan_img;
        }

        class ViewHolder02 {
            private CircleImageView qiushi_item02_img;
            private TextView qiushi_item02_nichen;
            private TextView qiushi_item02_time;
            private TextView qiushi_item02_desrc;
            private LinearLayout qiushi_item02_fenxiang_ll;
            private LinearLayout qiushi_item02_pinglun_ll;
            private TextView qiushi_item02_pinglun_text;
            private LinearLayout qiushi_item02_dianzan_ll;
            private TextView qiushi_item02_dianzan_text;
            private ImageView qiushi_item02_dianzan_img;
        }
        class ViewHolder03 {
            private CircleImageView qiushi_item03_img;
            private TextView qiushi_item03_nichen;
            private TextView qiushi_item03_time;
            private TextView qiushi_item03_desrc;
            private JCVideoPlayerStandard videoplayer;
            private LinearLayout qiushi_item03_fenxiang_ll;
            private LinearLayout qiushi_item03_pinglun_ll;
            private TextView qiushi_item03_pinglun_text;
            private LinearLayout qiushi_item03_dianzan_ll;
            private TextView qiushi_item03_dianzan_text;
            private ImageView qiushi_item03_dianzan_img;
        }
    }

}
